import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import storage from '../utils/storage'

// Components
import JJIndexLayout from '../layouts/JJIndexLayout.vue'
import JJHome from '../views/JJHome.vue'
import JJLogin from '../views/JJLogin.vue'
import { Message } from 'element-ui'

Vue.use(VueRouter)

const router = new VueRouter({
  mode: 'history',
  base: import.meta.env.BASE_URL,
  routes: [
    {
      path: '/login',
      name: 'login',
      component: JJLogin
    },
    {
      path: '/',
      component: JJIndexLayout,
      children: [
        {
          path: '',
          name: 'home',
          meta: {
            title: 'Home',
            auth: true
          },
          component: JJHome
        },
        {
          path: 'P0/O1',
          meta: {
            title: 'Option - 1',
            isNavTag: true,
            auth: true
          },
          component: () => import('../components/p0/JJOp1.vue')
        },
        {
          path: 'P0/O2',
          meta: {
            title: 'Option - 2',
            isNavTag: true,
            auth: true
          },
          component: () => import('../components/p0/JJOp2.vue')
        },
        {
          path: 'P0/O3',
          meta: {
            title: 'Option - 3',
            isNavTag: true,
            auth: true
          },
          component: () => import('../components/p0/JJOp3.vue')
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  const { isNavTag, title } = to.meta

  if (to.meta.auth && !storage.has('token')) {
    Message({
      message: 'Please log in first',
      type: 'error'
    })

    router.push({ name: 'login' })
  }

  if (isNavTag) {
    store.commit('addTag', { name: title, path: to.path })
  }

  next()
})

export default router
